package com.molihub.utils;

import com.molihub.entity.ResponseResult;
import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName: FileUploadUtils
 * @Description: 文件上传工具类
 * @author: GGBOY
 * @date 2020/2/11 18:08
 * @Version: 1.0
 **/
public class FileUploadUtils {
    private static Logger logger = LogUtils.getInstance(FileUploadUtils.class);
    /**
     * 文件上传工具类
     *
     * @param file 需要上传的文件
     * @return com.molihub.entity.ResponseResult
     * @author GGBOY
     * @date 2020/2/11
     */
    public static ResponseResult uploadImageWithPost(MultipartFile file) {
        ResponseResult responseResult = new ResponseResult();
        if (file == null) {
            return null;
        }
        String filename = file.getOriginalFilename();
        try {
            if (!"".equals(Objects.requireNonNull(filename).trim())) {
                File newFile = new File(filename);
                FileOutputStream outputStream = new FileOutputStream(newFile);
                outputStream.write(file.getBytes());
                outputStream.close();
                file.transferTo(newFile);
                AliyunOssUtil aliyunOssUtil = SpringUtils.getBean(AliyunOssUtil.class);
                String url = aliyunOssUtil.upLoad(newFile);
                if (url != null) {
                    responseResult.setSuccess(1);
                    responseResult.setUrl(url);
                    responseResult.setMessage("修改成功!");
                    logger.info("上传的图片URL地址为：" + url);
                } else {
                    responseResult.setSuccess(2);
                    responseResult.setMessage("类型错误");
                }
                //删除文件
                newFile.delete();
            }
        } catch (FileNotFoundException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        } catch (IOException e) {
            responseResult.setSuccess(0);
            responseResult.setMessage("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }

}
